package com.intexh.quickandroid.module.chat.ui.face;

import android.content.Context;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FaceParser {

    private static List<Face> faces;

    public static List<Face> readMap(Context mContext) {
        if (faces != null) {
            return faces;
        } else {
            faces = new ArrayList<Face>();
            XmlPullParser xmlpull = null;
            try {
                XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
                xmlpull = xppf.newPullParser();
                String[] files = mContext.getAssets().list(".");
                InputStream stream = mContext.getAssets().open("image.xml");
                xmlpull.setInput(stream, "UTF-8");
                int eventCode = xmlpull.getEventType();
                Face face = null;
                while (eventCode != XmlPullParser.END_DOCUMENT) {
                    switch (eventCode) {
                        case XmlPullParser.START_DOCUMENT: {
                            break;
                        }
                        case XmlPullParser.START_TAG: {
                            if (xmlpull.getName().equals("name")) {
                                face.key = xmlpull.nextText();
                            } else if (xmlpull.getName().equals("image")) {
                                face = new Face();
                            } else if (xmlpull.getName().equals("target")) {
                                face.value = xmlpull.nextText();
                            }
                            break;
                        }

                        case XmlPullParser.END_TAG: {
                            if (xmlpull.getName().equals("image")) {
                                faces.add(face);
                            }
                            break;
                        }
                        case XmlPullParser.END_DOCUMENT: {
                            System.out.println("parse emoji complete");
                            break;
                        }
                    }
                    eventCode = xmlpull.next();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return faces;
    }

    public static String getKeyByValue(Context context, String value) {
        if (faces == null) {
            faces = readMap(context);
        }
        for (Face face : faces) {
            if (face.key.equals(value)) {
                return face.value;
            }
        }
        return null;

    }
}
